const fse = require('fs-extra');
const { recursionFilePath } = require('./util');
const { logger } = require('./logger');

const fileExt = "meta";
const linkFileExts = ["png", "jpg"];    // 关联的文件类型
const targetPath = "../assets";
const normalPvrType = "pvrtc_2bits";
const highPvrType = "pvrtc_4bits";

const highAstcKeywords = ["_Face_m_"];
function checkHighAstc(filePath) {
    return highAstcKeywords.some((keyword) => filePath.includes(keyword));
}

/**
 * 格式化文件
 * @param {string} filePath 
 * @returns 
 */
function formatFile(filePath) {
    const fileInfo = filePath.split(".");
    if (fileInfo.length < 3) return;
    if (fileInfo[fileInfo.length - 1] !== fileExt) return;
    if (!linkFileExts.includes(fileInfo[fileInfo.length - 2])) return;

    const content = fse.readFileSync(filePath, 'utf8');
    try {
        obj = JSON.parse(content);
        if (!obj.platformSettings) return;

        const isHigh = checkHighAstc(filePath);
        const pvrType = isHigh ? highPvrType : normalPvrType;
        let platformSettings;
        if (isHigh) {
            platformSettings = {};
        } else {
            platformSettings = {
                "wechatgame": {
                    "formats": [{ "name": pvrType, "quality": "normal" }, { "name": "png", "quality": 99 }]
                }
            }
        }
        logger.log("name--:", filePath, JSON.stringify(platformSettings));
        if (JSON.stringify(obj.platformSettings) === JSON.stringify(platformSettings)) return;

        obj.platformSettings = platformSettings;
        fse.writeFileSync(filePath, JSON.stringify(obj, null, 2), 'utf8');
    } catch (error) {
        logger.error(`override file error ${filePath}`, error);
    }
}

logger.log("format meta start");
recursionFilePath(targetPath, formatFile);
logger.log("format meta done");